package cn.yto.print.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.OperatingSystem;
import oshi.util.FormatUtil;

import java.text.DecimalFormat;

public class SysMonitorUtil {

    private static final Logger logger = LoggerFactory.getLogger(SysMonitorUtil.class);

    public static void cpuMemoryMonitor() {

        SystemInfo systemInfo = new SystemInfo();
        HardwareAbstractionLayer hardware = systemInfo.getHardware();
        CentralProcessor processor = hardware.getProcessor();
        GlobalMemory memory = hardware.getMemory();
        OperatingSystem os = systemInfo.getOperatingSystem();

        // 显示系统基本信息
//        logger.info("系统基本信息：操作系统 - {}，处理器 - {}，物理核心数 - {}，逻辑核心数 - {}", os.getFamily() + " " + os.getVersionInfo(), processor.getProcessorIdentifier().getName(),
//                processor.getPhysicalProcessorCount(), processor.getLogicalProcessorCount());

        // 获取CPU负载
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long[] ticks = processor.getSystemCpuLoadTicks();

        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
        long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;

        // 格式化输出
        DecimalFormat df = new DecimalFormat("0.00%");
        logger.info("当前[CPU]使用 - 用户占用：{}；系统占用：{}；空闲：{}", df.format((double) user / totalCpu),
                df.format((double) cSys / totalCpu), df.format((double) idle / totalCpu));

        // 获取内存信息
        long totalMemory = memory.getTotal();
        long availableMemory = memory.getAvailable();
        long usedMemory = totalMemory - availableMemory;
        logger.info("当前内存使用 - 内存大小：{}；已用内存：{}；可用内存：{}", FormatUtil.formatBytes(totalMemory),
                formatPercentage(usedMemory, totalMemory), formatPercentage(availableMemory, totalMemory));
    }

    private static String formatPercentage(long part, long total) {
        if (total == 0) {
            return "0.00";
        }
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format((double) part / total * 100);
    }

    public static void main(String[] args) throws Exception {
        cpuMemoryMonitor();
    }

}
